import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';

import api from '@/api';
import req from '@/utils/req';

export const getUser = createAsyncThunk('user/getUser', () =>
  req.get<typeof initialState.info>(api.userInfo, {}, { hiddenMsg: true })
);
export const getUserProfits = createAsyncThunk('user/getUserProfits', () =>
  req.get<Pick<typeof initialState, 'coupon_cnt' | 'member_detail'>>(api.userProfits)
);

const initialState = {
  login: false,
  loaded: false,
  memberLoad: false,

  qrCode: 'https://www.baidu.com',
  accept: true,
  info: {
    company: '',
    position: '',
    uid: '',
    nickname: '',
    telephone: '',
  },
  coupon_cnt: 0,
  member_detail: {
    profit_id: '',
    type: 0,
    start_time: '',
    end_time: '',
  } as null | {
    profit_id: string;
    type: 0 | 1 | 2 | 3; // 1-月会员，2-季度会员，3-年会员
    start_time: string;
    end_time: string;
  },
  guid: '',
  showRightModal: false,
};

const user = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setState(state, action: PayloadAction<Partial<userState>>) {
      Object.assign(state, action.payload);
    },
  },
  extraReducers: (builder) => {
    builder.addCase(getUser.rejected, (state) => {
      state.login = false;
      state.loaded = true;
    });
    builder.addCase(getUser.fulfilled, (state, action) => {
      state.login = true;
      state.info = action.payload;
      state.loaded = true;
    });
    builder.addCase(getUserProfits.fulfilled, (state, action) => {
      state.coupon_cnt = action.payload.coupon_cnt;
      state.member_detail = action.payload.member_detail;
      state.memberLoad = true;
    });
  },
});

export type userState = typeof initialState;
export const userReducer = user.reducer;
export const userActions = user.actions;
export default user;
